package li.com.springaidemo.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.websocket.server.PathParam;
import li.com.springaidemo.common.R;
import li.com.springaidemo.pojo.*;
import li.com.springaidemo.server.WebSocketServer;
import li.com.springaidemo.service.AIService;
import li.com.springaidemo.service.HistoryService;
import li.com.springaidemo.service.ImgsService;
import li.com.springaidemo.service.MessageService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
//import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ai")
public class AIController {
//    记录不同用户与不同AI模型之间的对话 <不同用户，<不同的虚拟角色，对应的Message>>
    private static Map<Integer,Map<String,List<Message>>> chatMessage = new ConcurrentHashMap<>();
    private final AIService aiService;
    private final ImgsService imgsService;
    private final ChatClient chatClient;
    private final HistoryService historyService;
    private final OssController ossController;
    private final WebSocketServer webSocketServer;
    private final MessageService messageService;
    private final RedisTemplate<String, Object> redisTemplate;
//  TODO 切换到自己本地的AI
//    private final OllamaChatModel ollamaChatModel;

    public AIController(AIService aiService,ChatClient chatClient,ImgsService imgsService,HistoryService historyService,OssController ossController, WebSocketServer webSocketServer, MessageService messageService, RedisTemplate<String, Object> redisTemplate) {
        this.aiService = aiService;
        this.imgsService = imgsService;
        this.chatClient = chatClient;
        this.historyService = historyService;
        this.ossController=ossController;
        this.webSocketServer = webSocketServer;
        this.messageService = messageService;
        this.redisTemplate = redisTemplate;
    }
//    public AIController(AIService aiService,ChatClient chatClient,ImgsService imgsService,HistoryService historyService,OssController ossController, WebSocketServer webSocketServer, MessageService messageService, RedisTemplate<String, Object> redisTemplate, OllamaChatModel ollamaChatModel) {
//        this.aiService = aiService;
//        this.imgsService = imgsService;
//        this.chatClient = chatClient;
//        this.historyService = historyService;
//        this.ossController=ossController;
//        this.webSocketServer = webSocketServer;
//        this.messageService = messageService;
//        this.redisTemplate = redisTemplate;
//        this.ollamaChatModel = ollamaChatModel;
//    }

// 智能问答ai
    @GetMapping("/ai")
    public R ai(@RequestParam(value = "message",defaultValue = "你好") String message){
        String output = chatClient.prompt()
                .user(message)
                .call()
                .content();
//        if(ollamaChatModel!=null){
//            String output = ollamaChatModel.call(message);
//              return R.success(output);
//        }
//        return R.error("断开连接");
            return R.success(output);
    }
//    获取所有虚拟角色列表
    @GetMapping("/init")
    public R init(@RequestParam(value = "input",defaultValue = "")String input){
//        int i=1/0;
        QueryWrapper<Persona> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        if(input!=null&&!input.isEmpty()){
            queryWrapper.eq("id",input).or().like("name",input).or().like("include",input);
        }
        List<Persona> personas = aiService.getBaseMapper().selectList(queryWrapper);
        return R.success(personas);
    }
//    获得用户创建的某个虚拟角色
    @GetMapping("/getOneHistory")
    public R getHistoryPersona(@RequestParam(value = "id",defaultValue = "1")int id){
        History history = historyService.getById(id);
        if (history==null){
            return R.error("该角色未找到，请返回首页");
        }
        return R.success(history);
    }
//    获取所有用户创建的虚拟角色列表
    @GetMapping("/AllHistory")
    public R getAllHistoryPersonaList(@RequestParam(value = "input",defaultValue = "")String input){
        QueryWrapper<History> queryWrapper=new QueryWrapper<>();
        if(input!=null&&!input.isEmpty()){
            queryWrapper.eq("id",input).or().eq("user_id",input).or().like("name",input).or().like("user_name",input);
        }
        List<History> list = historyService.list(queryWrapper);
        return R.success(list);
    }
//    获取指定用户创建的虚拟角色列表
    @GetMapping("/history")
    public R getHistoryPersonaList(@RequestParam(value = "userId",defaultValue = "1")String userId){
        QueryWrapper<History> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<History> list = historyService.list(queryWrapper);
        return R.success(list);
    }
//    删除用户自己创建的虚拟角色
    @PostMapping("/historyDeletePersona")
    public R deleteHistoryPersona(@RequestBody History history){
        ossController.deleteImg(history.getImg());
        historyService.getBaseMapper().deleteById(history);
        redisTemplate.delete("history"+history.getId());
        return R.success();
    }
//    新增/修改用户自己创建的虚拟角色
    @PostMapping("/historyUpdatePersona")
    public R updateHistoryPersona(@RequestBody History history){
        History findHistory = historyService.getById(history.getId());
        history.setDescription(history.getDescription());
        if (findHistory==null){
            historyService.save(history);
        }else {
            historyService.updateById(history);
            redisTemplate.delete("history"+history.getId());
        }
//        修改角色信息之后通知用户
        webSocketServer.sendToUserClient(history.getUserId()+"","角色发生变更");
        return R.success();
    }
//    获取单个虚拟角色信息
    @GetMapping("/getPersona")
    public R getPersona(@PathParam(value = "name") String name){
        Persona persona = aiService.getOne(new QueryWrapper<Persona>().eq("object_name",name));
        if (persona==null){
            return R.error("该角色未找到，请返回首页");
        }
        return R.success(persona);
    }
//    获取所有虚拟角色列表（分页）
    @GetMapping("/page")
    public R getPersonaList(@RequestParam(value = "input",defaultValue = "")String input){
        QueryWrapper<Persona> queryWrapper=new QueryWrapper<>();
        if(input!=null&&!input.isEmpty()){
            queryWrapper.eq("id",input).or().like("name",input).or().like("object_name",input).or().like("include",input);
        }
        queryWrapper.orderByAsc("sort");
        List<Persona> list = aiService.list(queryWrapper);
        return R.success(list);
    }
//    修改|添加虚拟角色信息
    @PostMapping("/updatePersona")
    public R updatePersona(@RequestBody Persona persona){
        if(persona.getId()!=null){
            aiService.updateById(persona);
            redisTemplate.delete(persona.getObjectName());
        }else {
            if(persona.getBackimg().isEmpty()){
//                如果没有设置背景图，则将头像作为背景图
                persona.setBackimg(persona.getImg());
            }
            aiService.save(persona);
        }
//        修改置顶角色
        if(persona.getSort()==0){
            UpdateWrapper<Persona> updateWrapper=new UpdateWrapper<>();
            updateWrapper.set("sort",1);
            aiService.update(updateWrapper);
            aiService.updateById(persona);
        }
        return R.success();
    }
//    删除虚拟角色
    @PostMapping("/deletePersona")
    public R deletePersona(@RequestBody Persona persona){
//        删除头像
        ossController.deleteImg(persona.getImg());
        if(persona.getId()!=null){
    //        获取图库并删除
            for (Imgs personaImg : imgsService.list(new QueryWrapper<Imgs>().eq("persona_name", persona.getName()))) {
                ossController.deleteImg(personaImg);
            }
    //        删除角色
            aiService.getBaseMapper().deleteById(persona);
            redisTemplate.delete(persona.getObjectName());
        }
        return R.success();
    }
//    获取虚拟角色的所属图库
    @GetMapping("/persona/img")
    public R getImg(@RequestParam(value = "persona")String persona){
        List<Imgs> list = imgsService.getBaseMapper().selectList(new QueryWrapper<Imgs>().eq("persona_name", persona));
        List<String> imgs=new ArrayList<>();
        for (Imgs imgs1 : list) {
            imgs.add(imgs1.getUrl());
        }
        return R.success(imgs);
    }
//    获取所有虚拟角色的所属图库
    @GetMapping("/persona/AllImg")
    public R getAllImg(){
        List<Imgs> list = imgsService.list();
//        collect(Collectors.groupingBy(Imgs::getName))  分组
        Map<String, List<Imgs>> map = list.stream().collect(Collectors.groupingBy(Imgs::getPersonaName));
        System.out.println(map);
        return R.success(map);
    }
//    更新某个虚拟角色的图库
    @PostMapping("/updateImg")
    public R updateImg(@RequestBody List<Imgs> list){
        String personaName = list.get(0).getPersonaName();
        imgsService.remove(new QueryWrapper<Imgs>().eq("persona_name", personaName));
        imgsService.saveBatch(list);
        return R.success();
    }
//    虚拟角色的背景
    @GetMapping("/getBackImg")
    public R getBackImg(@PathParam("name") String name){
        Persona backImg = aiService.getOne(new QueryWrapper<Persona>().eq("object_name", name));
        if(backImg!=null){
            return R.success(backImg.getBackimg());
        }else {
            return R.error("未找到该角色");
        }
    }
//    向虚拟角色发送消息,接收消息
    @GetMapping("/persona")
    public R generation(@RequestParam(value = "persona",defaultValue = "pamu")String persona,@RequestParam(value = "id",defaultValue = "1")Integer id, @RequestParam(value = "message",defaultValue = "你好") String message) {
        MessageLog usermessageLog = new MessageLog();
        usermessageLog.setId(UUID.randomUUID().toString());
        usermessageLog.setUserid(id);
        usermessageLog.setPersonaname(persona);
        usermessageLog.setText(message);
        usermessageLog.setTime(LocalDateTime.now());
        usermessageLog.setType(1);
        messageService.saveto(usermessageLog);
        Map<String, List<Message>> userMessages = chatMessage.get(id);
        if(userMessages == null) {
            userMessages = new ConcurrentHashMap<>();
            chatMessage.put(id,userMessages);
        }
        List<Message> messages = userMessages.get(persona);
//        把这个集合传入到service里进行操作，返回值类型也为List<Message>
        messages = aiService.getMessages(persona,message, messages);

        for (Message message1 : messages) {
            System.out.println(message1);
        }
//        修改为本地AI
//        TODO if(ollamaChatModel != null){
        if(chatClient!=null){
            ChatResponse chatResponse = chatClient.prompt()
                    .messages(messages)
                    .call()
                    .chatResponse();
//            TODO ChatResponse chatResponse = ollamaChatModel.call(new Prompt(messages));
            String output=chatResponse.getResult().getOutput().getContent();
            messages = aiService.responseMessages(persona,chatResponse, messages);
            userMessages.put(persona,messages);
            chatMessage.put(id,userMessages);
//            聊天记录
            MessageLog personamessageLog = new MessageLog();
            personamessageLog.setId(UUID.randomUUID().toString());
            personamessageLog.setUserid(id);
            personamessageLog.setPersonaname(persona);
            personamessageLog.setText(output);
            personamessageLog.setTime(LocalDateTime.now());
            personamessageLog.setType(0);
            messageService.saveto(personamessageLog);
            return R.success(output);
        }else {
            return R.error("没有该虚拟角色");
        }
    }
//    向用户创建的虚拟角色发送消息,接收消息
    @GetMapping("/historyPersona")
    public R historyPersona(@RequestParam(value = "personaid",defaultValue = "pamu")String personaid,@RequestParam(value = "id",defaultValue = "1")Integer id, @RequestParam(value = "message",defaultValue = "你好") String message) {
        Map<String, List<Message>> userMessages = chatMessage.get(id);
        if(userMessages == null) {
            userMessages = new ConcurrentHashMap<>();
            chatMessage.put(id,userMessages);
        }
        List<Message> messages = userMessages.get(personaid);
//        把这个集合传入到service里进行操作，返回值类型也为List<Message>
        messages = historyService.getMessages(personaid,message, messages);

        for (Message message1 : messages) {
            System.out.println(message1);
        }
        if(chatClient!=null){
            ChatResponse chatResponse = chatClient.prompt()
                    .messages(messages)
                    .call()
                    .chatResponse();
            String output=chatResponse.getResult().getOutput().getContent();
            messages = historyService.responseMessages(personaid,chatResponse, messages);
            userMessages.put(personaid,messages);
            chatMessage.put(id,userMessages);
            return R.success(output);
        }else {
            return R.error("没有该虚拟角色");
        }
    }

//        prompt  提示词
//        String output = this.pamuChatClient.prompt()
//                user  用户信息，输入的数据
//                .user(message)
//                .system(user)
//                远程请求大模型
//                .call()
////                返回文本
//                .content();
//    produces = "text/html;charset=UTF-8"  配置请求头的信息，否则会出现乱码
//    @GetMapping(value = "/stream",produces = "text/html;charset=UTF-8")
//    public Flux<String> stream(@RequestParam(value = "user",defaultValue = "")String user,@RequestParam(value = "message",defaultValue = "给我讲一个笑话") String message) {
//        if(user!=null){
//            this.chatClient=chatClientBuilder.defaultSystem(user).build();
//        }
//        prompt  提示词
//        Flux<String> output = this.pamuChatClient.prompt()
//                user  用户信息，输入的数据
//                .user(message)
//                远程请求大模型，使用stream流的方式
//                .stream()
//                返回文本
//                .content();
//        return output;
//    }
}
